import re

def get_url(source, keywords):
    url = source.url + '+'.join(keywords.split())
    return url.encode('utf-8')

def get_formated_keywords(keywords):

    p = re.compile('("[^"]*")')
    quoted_k = p.split(keywords)

    keys = []
    for key in quoted_k:
        if key.startswith('"') and key.endswith('"'):
            keys.append(key)
        else:
            key = key.lower().strip()
            for k in key.split():
                if len(k) > 2: 
                    keys.append(k.strip('"'))

    proc_k = ' '.join(sorted(keys))
    return proc_k

def safe_unicode(obj, *args):
    """ 
        From Python Cookbook
        return the unicode representation of obj 
    """
    try:
        return unicode(obj, *args)
    except UnicodeDecodeError:
        # obj is byte string
        ascii_text = str(obj).encode('string_escape')
        return unicode(ascii_text)
    except:
        return obj
